package org.mcclone.jetty;

import com.google.gson.Gson;
import io.netty.util.internal.SystemPropertyUtil;
import org.apache.http.entity.ContentType;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.ServletHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by McClone on 2018/3/31.
 */
public class JettyServer {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8081);
        ServletHandler servletHandler = new ServletHandler();
        servletHandler.addServletWithMapping(HelloServlet.class, "/files");
        HandlerList handlerList = new HandlerList();
        handlerList.addHandler(new AbstractHandler() {
            @Override
            public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
                System.out.println(s);
            }
        });
        handlerList.addHandler(servletHandler);
        server.setHandler(handlerList);
        server.start();
        server.join();
    }

    public static class HelloServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType(ContentType.APPLICATION_JSON.getMimeType());
            resp.setStatus(HttpServletResponse.SC_OK);
            String[] result = new String[]{"1", "2"};
            resp.getWriter().println(new Gson().toJson(result));
            resp.getWriter().println(SystemPropertyUtil.get("user.dir"));
        }
    }
}
